import { Text, View } from 'native-base';
import { CommonStyle } from '../../../../common/commonStyle.ts';
import { TouchableOpacity } from 'react-native';
import React, { useContext, useEffect } from 'react';
import to from '../../../../utils/to.ts';
import LocationClass from '../../../../utils/LocationClass.ts';
import Tools from '../../../../utils/Tools.ts';
import { useAsyncEffect, useReactive } from 'ahooks';
import { navigate } from '../../../../common/navigationService.ts';
import { ProductSubmissionContext } from '../../productSubmission';

interface IAdditionalFormLocationProps {
  item: IGoodsAdditionalInfo;
  edit?: boolean;
  onChange: (value: string) => void;
}
interface IState {
  location: string;
  lat: number;
  lng: number;
  change?: (data: IState) => void;
}
export default function AdditionalFormLocation({ item, edit, onChange }: IAdditionalFormLocationProps) {
  const mapLocation = useContext(ProductSubmissionContext);
  const state = useReactive<IState>({
    location: '',
    lat: 0,
    lng: 0,
    change(data) {
      this.location = data.location;
      this.lat = data.lat;
      this.lng = data.lng;
    },
  });

  useAsyncEffect(async () => {
    const [err, res] = await to(LocationClass.getLocation());
    if (err) return;
    const latitudeLongitude = Tools.gpsCoordinateToBaiduCoordinate(res.coords.longitude, res.coords.latitude);
    const location = await Tools.getAddressFromCoordinates(latitudeLongitude.lng, latitudeLongitude.lat);
    state.change!({ location: location.forma_address, lat: latitudeLongitude.lat, lng: latitudeLongitude.lng });
  }, []);

  useEffect(() => {
    if (mapLocation) {
      const address = mapLocation.address;
      state.change!({ location: address.province + address.city + address.district + address.streetNumber + address.address, lat: mapLocation.lat, lng: mapLocation.lng });
    }
  }, [mapLocation]);

  useEffect(() => {
    if (state.location) onChange(JSON.stringify({ address: state.location, latitude: state.lat, longitude: state.lng }));
  }, [state.location]);

  return (
    <>
      <View flexDirection={'row'} alignItems={'center'} py={4}>
        <View width={'25%'} flexDirection={'row'}>
          {item.requiredFlag && !edit && (
            <Text marginRight={1} color={CommonStyle.price}>
              *
            </Text>
          )}
          <Text marginRight={2} fontSize={12}>
            {item.attrName}
          </Text>
        </View>
        <TouchableOpacity style={{ flex: 1 }} onPress={() => navigate('selectMapPoint', { backScreen: 'productSubmission' })}>
          <Text fontSize={12}>{state.location || '选择位置'}</Text>
          <Text fontSize={10} mt={1} color={CommonStyle.mainColor}>
            点击重新选择位置
          </Text>
        </TouchableOpacity>
      </View>
    </>
  );
}
